const express = require('express')
const UserModel = require('../../models/UserModel')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const {secret} = require('../../config/config')

const router = express.Router()
// 注册
router.post('/reg', (req, res, next) => {
    console.log(req.body);
    UserModel.create({
       ...req.body,
       password: md5(req.body.password) 
    }).then(data => {
        console.log(data);
        res.json({
            code: '0000',
            msg: '注册成功',
            data: data
        })
    }).catch(err => {
        res.json({
            code: '0000',
            msg: '注册失败',
            data: null
        })
        res.status(500).send('注册失败')
    })
})

// 登录
router.post('/login', (req, res, next) => {
    const {username, password} = req.body
    UserModel.findOne({username: username, password: md5(password)}).then(data => {
        console.log(data);
        if (!data) {
           return res.json({
                code: '2002',
                msg: '用户名或密码错误',
                data: null
            })
        }

        // 登陆成功，写入token
        const token = jwt.sign(
            {username: data.username, _id: data._id},
             secret, {
            expiresIn: 60 * 60 * 24 * 7
        }) 

        res.json({
            code: '0000',
            msg: '登陆成功',
            token: token
        })
    
    }).catch(err => {
        res.json({
            code: '2001',
            msg: '登陆失败',
            token: null
        })
    })
})

// // 退出登录省略，由前端销毁token退出登录
// router.post('/logout', (req, res, next) => {
//     req.session.destroy(() => {
//         res.render('success', {msg: '推出成功', url: '/login'})
//     })
// })




module.exports = router